<template>
  <a-card :bordered="false" :loading="loading">
    <DynamicForm
      :data-source="dataColumn"
      :model-data="{
        ...detailData,
        type: route.query?.parentId ? 2 : detailData?.type || 1,
        parentId: /^\d+$/.test(route.query?.parentId)
          ? parseInt(route.query?.parentId)
          : detailData.parentId || '',
        hidden: detailData.hidden === 'Y',
        permissions: getCheckedKeys(detailData?.permissions?.split(',')),
      }"
      @submit-form="submitForm"
      @cancel="closeTab"
    >
    </DynamicForm>
  </a-card>
</template>

<script setup lang="tsx">
  import { message } from 'ant-design-vue';
  import DynamicForm from '@/components/dynamicForm/index.vue';
  import useRequestDetail from '@/hooks/useRequestDetail';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import {
    createSysPermission,
    getSysPermissionTree,
    sysPermissionApi,
    updateSysPermission,
  } from '@/api/system/permission';

  defineOptions({
    name: 'sysPermissionDetail',
  });
  const route = useRoute();
  const tabsViewStore = useTabsViewStore();
  const treeData = ref<{ [x: string]: any }[]>([]);
  /** 菜单类型 1: 目录 | 2: 菜单 | 3: 权限 */
  const isDir = (type: API.Menu['type']) => type === 1;
  const isMenu = (type: API.Menu['type']) => type === 2;
  const isPerm = (type: API.Menu['type']) => type === 3;
  const dataColumn = ref([
    {
      field: 'type',
      component: ComponentsTypeEnum.RadioGroup,
      label: '类型',
      rules: [{ required: true, type: 'number', message: '请选择类型' }],
      componentProps: {
        defaultValue: 1,
        options: [
          {
            label: '目录',
            value: 1,
          },
          {
            label: '菜单',
            value: 2,
          },
          {
            label: '权限',
            value: 3,
          },
        ],
      },
    },
    {
      field: 'layout',
      component: ComponentsTypeEnum.RadioGroup,
      label: 'Layout',
      vIf: (formModel) => isMenu(formModel['type']),
      rules: [{ required: true, type: 'string', message: '请选择布局类型' }],
      componentProps: {
        defaultValue: 'default',
        options: [
          {
            label: 'default',
            value: 'default',
          },
          {
            label: 'full',
            value: 'full',
          },
        ],
      },
    },
    {
      field: 'title',
      component: ComponentsTypeEnum.Input,
      label: '节点名称',
      rules: [{ required: true }],
    },
    {
      field: 'parentId',
      component: ComponentsTypeEnum.TreeSelect,
      label: '上级节点',
      componentProps: {
        fieldNames: {
          label: 'title',
          value: 'id',
          children: 'children',
        },
        treeData,
      },
    },
    {
      field: 'path',
      component: ComponentsTypeEnum.Input,
      label: '路径',
      vIf: (formModel) => !isPerm(formModel['type']),
      rules: [{ required: true }],
    },
    {
      field: 'redirect',
      component: ComponentsTypeEnum.Input,
      label: '跳转路径',
      vIf: (formModel) => isDir(formModel['type']),
      rules: [{ required: true }],
    },
    {
      field: 'component',
      component: ComponentsTypeEnum.Input,
      label: '组件名',
      vIf: (formModel) => isMenu(formModel['type']),
      rules: [{ required: true }],
    },
    {
      field: 'key',
      component: ComponentsTypeEnum.Input,
      label: 'key值',
      rules: [{ required: true }],
    },
    {
      field: 'sort',
      component: ComponentsTypeEnum.Input,
      label: '排序',
    },
    {
      field: 'icon',
      component: ComponentsTypeEnum.IconsSelect,
      label: '节点图标',
      vIf: (formModel) => !isPerm(formModel['type']),
    },
    {
      field: 'hidden',
      component: ComponentsTypeEnum.ASwitch,
      label: '隐藏路由',
      vIf: (formModel) => !isPerm(formModel['type']),
      componentProps: {
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
    },
  ]);
  const { detailData, loading } = useRequestDetail({
    apiKey: sysPermissionApi.sysPermissionDetail,
    initParams: route?.query,
    isMount: !!route.query?.id,
  });
  const getPermissionTree = async () => {
    const data = await getSysPermissionTree();
    if (data) {
      treeData.value = data;
      delKey(data);
    } else {
      treeData.value = [];
    }
  };

  const getCheckedKeys = (permissions) => {
    const checkedKeys: any[] = [];
    if (!permissions) return [];
    const filterKeys = (list) => {
      list.forEach((item) => {
        if (permissions.indexOf(`${item.id}`) !== -1) {
          if (item.children && item.children.length) {
            let isChildren = true;
            item.children.forEach((childrenItem) => {
              if (permissions.indexOf(`${childrenItem.id}`) === -1) {
                isChildren = false;
              }
            });
            if (isChildren) {
              checkedKeys.push(item.id);
            }
            filterKeys(item.children);
          } else {
            checkedKeys.push(item.id);
          }
        } else {
          if (item.children && item.children.length) {
            filterKeys(item.children);
          }
        }
      });
    };
    filterKeys(treeData.value);
    return checkedKeys;
  };

  const delKey = (data) => {
    data.forEach((item) => {
      delete item.key;
      if (item.children && item.children.length) {
        delKey(item.children);
      }
    });
  };
  const submitForm = async (params) => {
    const id = route?.query?.id;
    params.hidden = params.hidden ? 'Y' : 'N';
    const res = id
      ? await updateSysPermission({ ...params, id })
      : await createSysPermission(params);
    if (res) {
      message.success(res?.msg);
      closeTab();
    }
  };

  const closeTab = () => {
    tabsViewStore.closeCurrentTab(route);
  };
  onMounted(async () => await getPermissionTree());
</script>

<style></style>
